import { defineComponent, reactive, ref, watch, nextTick } from 'vue'
import { ElMessage, ElTable, ElTableColumn, ElPagination, ElImage, ElTag, ElFormItem, ElForm, ElSelect, ElButton, ElOption, ElTooltip, ElIcon, ElEmpty, ElPopover, ElTabs, ElTabPane, ElDescriptions, ElDescriptionsItem } from 'element-plus'
import { QuestionFilled, Picture as IconPicture } from '@element-plus/icons-vue'
import dayjs from 'dayjs'

import Drawer from '@renderer/components/drawer'
import { useExpose } from '@renderer/utils'
import { toBuffer } from '@renderer/utils/utils'
import { SELECT_LABEL_TYPE_MAP } from '@renderer/enums/common'
import { getUnlimitedSendDetail, getUnlimitedSendDetailList, exportUnlimitedSendDetailExport, restartTask } from '@renderer/ajax/api/infiniteSend'

import { renderFileAvatar } from '../utils/index'
import styles from './Detail.module.scss'

const { ipcRenderer } = require("electron");
const fs = require('fs')

export default defineComponent({
    name: 'Detail',
    setup() {
        const tabsValue = ref('list')
        const drawerData = reactive({
            visible: false,
            title: '活动标题',
            width: '860px'
        })
        
        const state = reactive({
            row: {},
            params: {
                Id: '',
                Title: '', // 标题
                Status: 0, // 状态
                Page: 1,
                PageSize: 15
            },
            list: [],
            Status: 0, // 0 全部 1 未发送 2 已发送 4 发送失败
            StatusOption: [
                { name: '全部状态', id: 0 },
                { name: '未发送', id: 1 },
                { name: '已发送', id: 2 },
                { name: '发送失败', id: 3 }
            ],
            total: 0,
            Data: {
                id: 0, // ID 不为0 为编辑
                title: "这是标题", // 标题
                type: 1, // 1 客户群发 2 客户群群发
                custFilterEnable: 2, // 1 无过滤 2 标签过滤/客户群筛选 3 客户群标签过滤(只有 type 类型为客户群群发的时候生效)  
                createdBetween: [], // 好友添加时间 客户群发&过滤时生i奥
                 // 客户群发时生效 & custFilterEnable = 2
                custGroupList: [],
                custFilter: { // 客户标签
                    filterType: 1, // 1 包含任意、 2 包含所有 3 不包含任意 4 不包含所有 5 标签为空 6 标签不为空
                    tags: []
                },
                custExcludeFilter: { // 排除客户标签
                    filterType: 1, // 1 包含任意、 2 包含所有 3 不包含任意 4 不包含所有 5 标签为空 6 标签不为空
                    tags: []
                },
                isSpecifySendTime: false, // 是否定时发送时间
                specifySendTime: "", // 允许为 null， 为 null时立即发送 
                // 发送内容
                content: [],
                status: 1,
                // 状态的中文
                statusMsg: '',
                // 预计客户/群聊的数量
                childTaskCount: 0,
                createdAt: "Date"
            },
            selectList: []
        })
        const onExport = async () => {
            const res: any = await exportUnlimitedSendDetailExport({ Id: state.Data.id, Title: state.params.Title, Status: state.params.Status })
            // res && ElMessage.success('导出成功')
            let params = {
                title: '请选择下载文件的目录',
                buttonLabel: '保存',
                pathName: `${state.Data.title || ''}_${dayjs(state.Data.createdAt).format('YYYY_MM_DD')}.xlsx`,
            }
            let buf = toBuffer(res)
            ipcRenderer.invoke("open-savebox", params).then((res) => {
                fs.writeFileSync(res.filePath, buf)
                res && ElMessage.success('导出成功')
            });
        }
        /**
         * 打开详情弹窗初始化
         * @param row 表格某一行的数据
         */
        const onState = async (row: any) => {
            drawerData.visible = true
            // 处理弹窗标题
            drawerData.title = `${row.Title} (${row.StatusMsg || '--'})`

            state.row = row
            state.params = { Id: row.Id, Title: state.params.Title, Status: state.params.Status, Page: state.params.Page, PageSize: state.params.PageSize }
            const res: any = await Promise.allSettled([getUnlimitedSendDetail({ id: row.Id }), getUnlimitedSendDetailList(state.params)])

            const [dataRes, listRes] = res
            if (dataRes.status === 'fulfilled') {
                state.Data = dataRes.value
            }

            // 拿到数据先处理一下封面的问题
            state.Data.content?.forEach(async item => {
                let avatarUrl = renderFileAvatar(item.fileInfo?.name, item.type)
                item.avatarUrl = avatarUrl
            })

            if (listRes.status === 'fulfilled') {
                state.list = listRes.value.data || []
                state.total = listRes.value.total || 0
            }
        }
        const getList = async () => {
            const res: any = await getUnlimitedSendDetailList(state.params)
            state.list = res.data || []
            state.total = res.total || 0
        }
        let timeout: any
        const onSearch = () => {
            if (timeout) clearTimeout(timeout)
            timeout = setTimeout(async () => {
                getList()
            }, 400)
        }

        const onSizeChange = (v: number) => {
            state.params.Page = 1;
            getList()
        };
        const onCurrentChange = (v: number) => {
            getList()
        };
        let timer: any = null
        // 开启定时器
        const startTimer = () => {
            timer = setInterval(() => {
                getList()
            }, 5000)
        }
        // 关闭定时器
        const closeTime = () => {
            clearInterval(timer)
            state.params.Id = '',
            state.params.Title = '',
            state.params.Status = 0
        }


        watch(
            () => drawerData.visible,
            async (v) => {
                if (v) {
                    startTimer()
                    resetState()
                } else {
                    closeTime()
                }
            }
        )

        /**
         * 重置页面的状态
         */
        const resetState = () => {
            state.params.Page = 1
            state.params.PageSize = 15
            tabsValue.value = 'list'
            selectList.length = 0
            state.Data = {}
        }

        /* ----------------------------选择发送-start---------------------------- */
        const selectList = reactive([])
        const onSend = async (type: string, row?: any) => {
            let IdList = []
            if (type == '1') {
                IdList = [row.id]
            } else if (type == '2') {
                IdList = []
            } else if (type == '3') {
                if (!selectList.length) {
                    ElMessage.warning('请选择需要重新发送的数据')
                    return
                }
                IdList = selectList.map(el => el.id)
            }
            let params = {
                taskId: state.params.Id,
                IdList: IdList
            }
            restartTask(params)
        }
        const onSelectionChange = (val?: any) => {
            selectList.length = 0
            selectList.push(...(val || []))
        }
        /* ----------------------------选择发送-end---------------------------- */


        useExpose({
            onState
        })
        // 发送状态
        const renderError = (row) => {
            const arr = ['', '未发送', '已发送', '发送失败', '已通过']
            return (
                <>
                    {!row.errorMsg ? (
                        <div class={styles.error}>{arr[row.sendStatus]}</div>
                    ) : (
                        <div class={styles.error}>
                            {arr[row.sendStatus]}
                            <ElTooltip class="box-item" effect="dark" content={row.errorMsg} placement="top">
                                <ElIcon>
                                    <QuestionFilled />
                                </ElIcon>
                            </ElTooltip>
                        </div>
                    )}
                </>
            )
        }
        const renderAdd = () => {
            return state.Data?.type == 1 ? '客户群发' : state.Data?.type == 2 ? '客户群群发' : '未知'
        }
        // 渲染客户/群聊
        const renderGroup = () => {
            const detailInfo = state.Data

            // 选择群聊选择客户的文本
            const groupConfig = {
                // 客户群发
                1: {
                    all: `全部客户（共${detailInfo.childTaskCount}个客户）`,
                    filter: `筛选客户（共${detailInfo.childTaskCount}个客户）`,
                    renderFilter: () => renderFilterTag()
                },
                // 客户群群发
                2: {
                    all: `全部群聊（共${detailInfo.childTaskCount}个群聊）`,
                    filter: {
                        2: `选择企微群（共${detailInfo.childTaskCount}个群聊）`,
                        3: `按客户标签选择群聊（共${detailInfo.childTaskCount}个群聊）`,
                    }[detailInfo.custFilterEnable],
                    renderFilter: () => detailInfo.custFilterEnable === 2 ? renderGroupList() : renderFilterTag()
                }
            }

            // 客户群发
            if (detailInfo.custFilterEnable === 1) {
                return groupConfig[detailInfo.type]?.all || '--'
            }

            // 渲染群聊列表
            const renderGroupList = () => {
                return <div class={styles.groupSelect} >
                    {
                        detailInfo.custGroupList?.map(item => {
                            return <div key={item.id} class={styles.groupItem}>{item.name || '--'}</div>
                        })
                    }
                </div>
            }

            // 渲染过滤标签
            const renderFilterTag = () => {

                const renderTags = (tagKey, label = '') => {
                    const filterTypeLabel = SELECT_LABEL_TYPE_MAP[detailInfo[tagKey]?.filterType]
                    if (filterTypeLabel) {
                        return <ElDescriptionsItem label={`${label}${filterTypeLabel}：`}>
                        <span class={styles.custTags}>
                            { detailInfo[tagKey]?.tags?.length ? detailInfo[tagKey].tags.map((item, index) => {
                                return <ElTag type={item.isDelete ? 'info' : undefined} >{item.name}</ElTag>
                            }) : '--'}
                        </span>
                        </ElDescriptionsItem>
                    }
                }

                return <div class={styles.custFilter}>
                    <ElDescriptions column={1}>
                        <ElDescriptionsItem label="添加时间：">
                            <span>{detailInfo.createdBetween?.join('~') || '--'}</span>
                        </ElDescriptionsItem>
                        {renderTags('custFilter')}
                        {renderTags('custExcludeFilter', '排除')}
                    </ElDescriptions>
                </div>
            }
            return <div>
                <div>{groupConfig[detailInfo.type]?.filter || '--'}</div>
                {groupConfig[detailInfo.type]?.renderFilter?.()}
            </div>
        }

        // 渲染发送时间
        const renderSendDate = () => {
            const detailInfo = state.Data
            
            if (typeof detailInfo.isSpecifySendTime === 'undefined') {
                return '--'
            }

            return detailInfo.isSpecifySendTime ? `定时发送 (${detailInfo.specifySendTime})` : '立即发送'
        }

        // 渲染发送内容
        const renderContent = () => {
            const detailInfo = state.Data
            if (!detailInfo.content?.length) {
                return '--'
            }
            return <div class={styles.sendContent} >
                {
                    detailInfo.content.map(item => {
                        // 渲染文本
                        if (item.type === 1) {
                            return <div class={styles.sendContentItem}>{item.content}</div>
                        }
                        // 渲染图片/视频/文件
                        if ([2, 3, 4].includes(item.type)) {
                            return <div class={`${styles.sendContentItem} ${styles.sendContentItemFile}`}>
                                <ElImage
                                    class={styles.contentFileUrl}
                                    src={item.avatarUrl}
                                />
                                <div class={styles.contentFileName}>{item.fileInfo?.name}</div>
                            </div>
                        }

                        return <div class={styles.sendContentItem}>--</div>
                    })
                }
            </div>
        }

        const renderInfo = (row: any) => (
            <div class={styles.column_info}>
                <ElImage
                    class={styles.avatar}
                    src={row.custAvatorUrl}
                    vSlots={{
                        error: () => (
                            <elIcon class={styles.avatar}>
                                <IconPicture />
                            </elIcon>
                        )
                    }}
                />
                <div class={styles.column_info_name}>{row.custName}</div>
            </div>
        )
        const renderDate = () => {
            return state.Data?.createdAt || '--'
        }
        const renderSendButton = (row: any) => {
            return <div>
                {
                    row.sendStatus == 3 ?
                        <ElButton size="small" onClick={() => onSend('1', row)}>
                            重新发送
                        </ElButton>
                        : ''
                }
            </div>
        }
        return () => (
            <>
                <Drawer state={drawerData}>
                    {{
                        default: () => (
                            <div class={styles.drawer_content}>
                                <ElTabs vModel={tabsValue}>
                                    <ElTabPane label="群发明细" name="list">
                                        <ElForm class={styles.search} inline={true}>
                                            <div class={styles.fun}>
                                                <ElFormItem label={state.Data.type === 1 ? '客户昵称' : '群名称'}>
                                                    <el-input class={styles.inp} vModel={state.params.Title} onInput={onSearch} clearable placeholder={`请输入${state.Data.type === 1 ? '客户昵称' : '群名称'}搜索`} />
                                                </ElFormItem>
                                                <ElFormItem label="发送状态">
                                                    <ElSelect
                                                        style="width:100%"
                                                        vModel={state.params.Status}
                                                        placeholder="请选择"
                                                        onChange={getList}
                                                        vSlots={{
                                                            default: () => (
                                                                <>
                                                                    {state.StatusOption.map((item) => (
                                                                        <ElOption key={item.id} label={item.name} value={item.id} />
                                                                    ))}
                                                                </>
                                                            )
                                                        }}
                                                    />
                                                </ElFormItem>
                                                <ElFormItem>
                                                    <ElButton class={styles.export_btn} type="primary" onClick={onExport}>
                                                        导出
                                                    </ElButton>
                                                </ElFormItem>
                                            </div>
                                        </ElForm>
                                        <div class={styles.search_send_btn}>
                                            <ElPopover
                                                placement={'top-start'}
                                                width={220}
                                                trigger="hover"
                                                vSlots={{
                                                    reference: () => (
                                                        <ElButton type="primary">
                                                            发送
                                                        </ElButton>
                                                    ),
                                                    default: () => (
                                                        <div>
                                                            <ElButton type="primary" onClick={() => onSend('2')}>
                                                                全量发送
                                                            </ElButton>
                                                            <ElButton type="primary" onClick={() => onSend('3')}>
                                                                批量发送
                                                            </ElButton>
                                                        </div>
                                                    )
                                                }}
                                            />
                                        </div>
                                        <div class={styles.table}>
                                            <ElTable
                                                height="calc(100vh - 370px)"
                                                data={state.list}
                                                row-key="id"
                                                onSelectionChange={onSelectionChange}
                                                vSlots={{
                                                    default: () => (
                                                        <>
                                                            <ElTableColumn type="selection" width="60" reserve-selection />
                                                            <ElTableColumn label={state.Data.type == 1 ? '客户信息' : state.Data.type == 2 ? '客户群信息' : '未知'} minWidth="120" vSlots={{ default: ({ row }) => renderInfo(row) }} />
                                                            <ElTableColumn label="发送时间" width="170" prop="CreatedAt" vSlots={{ default: ({ row }) => row.sendTime || '--' }} />
                                                            <ElTableColumn label="发送状态" width="120" vSlots={{ default: ({ row }) => renderError(row) }} />
                                                            <ElTableColumn label="操作" width="120" vSlots={{ default: ({ row }) => renderSendButton(row) }} />
                                                        </>
                                                    ),
                                                    empty: () => <ElEmpty />
                                                }}
                                            />
                                        </div>
                                        <ElPagination
                                            class={styles.pagination}
                                            vModel:currentPage={state.params.Page}
                                            vModel:pageSize={state.params.PageSize}
                                            page-sizes={[15, 30, 50, 100]}
                                            background
                                            layout="total,  prev, pager, next,sizes, jumper"
                                            total={state.total}
                                            onSizeChange={onSizeChange}
                                            onCurrentChange={onCurrentChange}
                                        />
                                    </ElTabPane>
                                    <ElTabPane label="任务详情" name="detail">
                                        <div class={styles.info}>
                                            <ElDescriptions column={1}>
                                                <ElDescriptionsItem label="群发类型：">
                                                    {renderAdd()}
                                                </ElDescriptionsItem>
                                                <ElDescriptionsItem label={`${state.Data?.type == 1 ? '选择客户' : '选择群聊'}：`} >
                                                    {renderGroup()}
                                                </ElDescriptionsItem>
                                                <ElDescriptionsItem label="发送时间：">
                                                    {renderSendDate()}
                                                </ElDescriptionsItem>
                                                <ElDescriptionsItem label="发送内容：">
                                                    {renderContent()}
                                                </ElDescriptionsItem>
                                                <ElDescriptionsItem label="创建时间：">
                                                    {renderDate()}
                                                </ElDescriptionsItem>
                                            </ElDescriptions>
                                        </div>
                                    </ElTabPane>

                                </ElTabs>
                            </div>
                        )
                    }}
                </Drawer>
            </>
        )
    }
})
